#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QLineEdit>
#include <QDoubleValidator>
#include <QLabel>
#include <QHBoxLayout>

MainWindow::MainWindow(QWidget *parent)
    : QDialog(parent)
{

    setWindowTitle("计算器");
    leftNum = new QLineEdit(this);
    leftNum->setAlignment(Qt::AlignRight);
    leftNum->setValidator(new QDoubleValidator(this));
    operat = new QLabel("+", this);
    rightNum = new QLineEdit(this);
    rightNum->setAlignment(Qt::AlignRight);
    rightNum->setValidator(new QDoubleValidator(this));
    equal = new QPushButton("=", this);
    equal->setEnabled(false);
    resNum = new QLineEdit(this);
    resNum->setAlignment(Qt::AlignRight);
    resNum->setReadOnly(true);

    QHBoxLayout* layout = new QHBoxLayout();
    layout->addWidget(leftNum);
    layout->addWidget(operat);
    layout->addWidget(rightNum);
    layout->addWidget(equal);
    layout->addWidget(resNum);
    setLayout(layout);
    connect(leftNum, SIGNAL(textChanged(QString)), this, SLOT(enableButton(void)));
    connect(rightNum, SIGNAL(textChanged(QString)), this, SLOT(enableButton(void)));
    connect(equal, SIGNAL(clicked(void)), this, SLOT(calcClicked(void)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::enableButton()
{
    bool leftOk, rightOk;
    leftNum->text().toDouble(&leftOk);
    rightNum->text().toDouble(&rightOk);
    equal->setEnabled(leftOk && rightOk);
}

void MainWindow::calcClicked()
{
    double res = leftNum->text().toDouble() + rightNum->text().toDouble();
    QString resStr = QString::number(res);
    resNum->setText(resStr);
}

